import axios from 'axios'
import { Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Vue from 'vue'

// create an axios instance
const service = axios.create({
  baseURL: '/api' // url = base url + request url
})

// request interceptor
service.interceptors.request.use(
  config => {
    // if (config.loading) {
    //   Vue.prototype.$startLoading()
    // }
    if (getToken()) {
      config.headers['Authorization'] = getToken()
    }
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  response => {
    // Vue.prototype.$endLoading()
    const res = response.data
    if (res.code !== 200) {
      Message.error(res.message)
    }
    switch (res.code) {
      case 200:
        if (response.config.method.toLowerCase() !== 'get') {
          Message({
            message: res.message,
            type: 'success'
          })
        }
        return res.data
        break
      case 401:
        store.dispatch('user/logout')
        break
    }
    return Promise.reject(res.message)
  },
  error => {
    Vue.prototype.$endLoading()
    console.log('err' + error) // for debug
    Message({
      message: error.message,
      type: 'error'
    })
    return Promise.reject(error)
  }
)

export default service
